// 实现一个控制并发函数，接受并发参数

class PromiseQueue {
    constructor(options = {}) {
        this.concurrency = options.concurrency || 1;
        this.currentCount = 0;
        this.pendingList = [];

    }

    add(task) {
        this.pendingList.push(task);
        // 权重与限制可一再这里排序
        this.run()
    }

    run() {
        if (this.pendingList.length == 0 || this.concurrency === this.currentCount) {
            return
        }
        this.currentCount++;
        const fn = this.pendingList.shift();

        const promise = fn();
        promise.then(this.completeOne.bind(this)).catch(this.completeOne.bind(this))
    }

    completeOne() {
        this.currentCount--;
        this.run();
    }
}


let queue = new PromiseQueue(3)
urls.forEach(url => {
    queue.add(() => loadImage(url))
})

// 实现一个控制并发函数，接受并发参数

class PromiseQueue {
    constructor(options = {}) {
        this.concurrency = options.concurrency || 1;
        this.currentCount = 0;
        this.pendingList = [];

    }

    add(task) {
        this.pendingList.push(task);
        this.run()
    }

    run() {
        if (this.pendingList.length == 0 || this.concurrency === this.currentCount) {
            return
        }
        this.currentCount++;
        const { fn } = this.pendingList.sort((a, b) => b.priority - a.priority).shift();
        // const fn = this.pendingList.shift();

        const promise = fn();
        promise.then(this.completeOne.bind(this)).catch(this.completeOne.bind(this))
    }

    completeOne() {
        this.currentCount--;
        this.run();
    }
}


let queue = new PromiseQueue(3)

const formatTask = (url) => {
    return {
        fn: () => loadImage(url),
        priority: url.priority
    }
}
urls.forEach(task => {
    queue.add(formatTask(task))
})

const heightProiority = {
    priority: 10,
    info: "high!!!",
    time: 2000
}


// https://juejin.cn/post/6998194847408472100?utm_source=gold_browser_extension